<?php

namespace builder\test\controllers;

use builder\base\BaseController;
use builder\export\ExportBuilder;
use builder\helper\H5;
use builder\helper\Str;
use builder\helper\T;
use builder\table\TableBuilder;

// Table Example
ini_set('memory_limit', '1G');
class TableController extends BaseController
{
    public $publicActions = ['index', 'demo', 'export'];

    CONST DATA_TOTAL = 50000;

    /**
     * 生成数据
     * @return \Generator
     */
    protected function getData()
    {
        for ($i = 0; $i < self::DATA_TOTAL; $i++) {
            yield $i;
        }
    }

    //demo
    public function actionIndex()
    {
        $tableBuilder = TableBuilder::instance(['id' => 'Table_Index_Table']);
        if ($this->isAjax) {
            $data = [];
            foreach ($this->getData() as $i) {
                $data[] = ['id' => $i + 1, 'name' => Str::random(5), 'age' => rand(16, 50), 'class' => 'Grade ' . ($i + 1), 'county' => 'China', 'sex' => 'Man'];
            }
            $tableBuilder->setPage(true)->setQuery($data)
            ->setColumns([
                'id',
                'name',
                'age' => function ($row) {
                    return H5::badge($row['age']);
                },
                'class',
                'county',
                'sex',
            ]);
        } else {
            $t = date('t');
            $nowRange = T::createRangeDate('now');
            $tableBuilder->setTitle('Table')
                ->setPage(true)
                ->setPartial(!!@$this->get['_partial'])
                ->registerPointcut(
                    H5::alert('这是一个嵌入式内容。', 'normal', false)
                )
                ->setLineStyle(['height' => 'auto'])
                ->setCss('.layui-table-page{text-align: right;}')
                ->setAutoSort(false)
                ->setTableHead([
                    $this->tableHead->checkbox(),
                    $this->tableHead->field('id')->title('ID')->sort(),
                    $this->tableHead->field('name')->title('Name'),
                    $this->tableHead->field('age')->title('Age')->sort(),
                    $this->tableHead->field('class')->title('Class'),
                    $this->tableHead->field('county')->title('County'),
                    $this->tableHead->field('sex')->title('Sex'),
                    $this->tableHead->toolbar()->title('操作'),
                ])
                ->setColumnFilter()
                ->setToolbarPrint()
                ->setToolbarExports()
                ->setToolbarRefresh()
                ->setToolbarCustom([
                    $this->toolbarCustom->modal()->title('导 出')->route('ymtest/table/export')->width(730)->height(520)->urlAttachFilter(),
                    $this->toolbarCustom->ajax()->title('请求按钮')->route('ymtest/table/demo')->method('post')->params(['id']),
                    $this->toolbarCustom->page()->title('页面按钮')->route('ymtest/table/demo')->params(['test' => 1])->targetBlank(),
                    $this->toolbarCustom->modal()->title('新 增')->route('ymtest/table/demo'),

                    $this->toolbarCustom->dropdown()->title('更多操作I')->icon('bi bi-arrow-up-left-square')->btnClass('layui-btn-primary')->toolbarDropdown([
                        $this->toolbarDropdown->modal()->title('新增一条记录1')->icon('bi bi-1-square-fill')->uiClass('text-danger')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->ajax()->title('新增一条记录2')->icon('bi bi-2-square-fill')->route('ymtest/table/demo')->method('post')->params(['id']),
                        $this->toolbarDropdown->page()->title('新增一条记录3')->icon('bi bi-3-square-fill')->route('ymtest/table/demo')->targetBlank(),
                    ]),
                    $this->toolbarCustom->dropdown()->positionRight()->title('更多操作II')->icon('bi bi-arrow-up-left-square')->toolbarDropdown([
                        $this->toolbarDropdown->modal()->title('新增一条记录1')->icon('bi bi-1-square-fill')->uiClass('text-danger')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->modal()->title('新增一条记录2')->icon('bi bi-2-square-fill')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->modal()->title('新增一条记录3')->icon('bi bi-3-square-fill')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->modal()->title('新增一条记录4')->icon('bi bi-4-square-fill')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->modal()->title('新增一条记录5')->icon('bi bi-5-square-fill')->route('ymtest/table/demo'),
                    ]),
                    $this->toolbarCustom->dropdown()->positionBottom()->title('更多操作III')->icon('bi bi-arrow-up-left-square')->btnClass('layui-btn-theme')->toolbarDropdown([
                        $this->toolbarDropdown->modal()->title('新增一条记录1')->icon('bi bi-1-square-fill')->uiClass('text-danger')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->modal()->title('新增一条记录2')->icon('bi bi-2-square-fill')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->modal()->title('新增一条记录3')->icon('bi bi-3-square-fill')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->modal()->title('新增一条记录4')->icon('bi bi-4-square-fill')->route('ymtest/table/demo'),
                        $this->toolbarDropdown->modal()->title('新增一条记录5')->icon('bi bi-5-square-fill')->route('ymtest/table/demo'),
                    ]),
                ])
                ->setToolbarFilter([
                    'b' => $this->toolbarFilter->datetime()->label('创建日期')->uiClass('w-auto float-none')->style('width:300px;')->quickChoice([
                        '今天' => $nowRange,
                        '昨日' => T::createRangeDate('-1 day', '-1 day'),
                        '近3日' => T::createRangeDate('-2 days'),
                        '近7日' => T::createRangeDate('-6 days'),
                        '近'.$t.'日' => T::createRangeDate('-'.($t-1).' days'),
                    ])->defaultValue($nowRange),
                    'keyword' => $this->toolbarFilter->text()->label('关键词')->defaultValue('20250254148933333300000000002547')->help('这是一个帮助文本。')->uiClass('w-350'),
                    'a' => $this->toolbarFilter->select()->label('下拉框')->options([1, 2, 3])->uiClass('w-350'),
                    'h' => $this->toolbarFilter->selectLayui()->label('通天塔')->options([
                        ['value' => '孙悟空', 'label' => '孙悟空', 'disabled' => false],
                        ['value' => '猪八戒', 'label' => '猪八戒', 'disabled' => false],
                        ['value' => '沙和尚', 'label' => '沙和尚', 'disabled' => false],
                        ['value' => '唐生', 'label' => '唐生', 'disabled' => false],
                        ['value' => '李静', 'label' => '李静', 'disabled' => false],
                        ['value' => '哪吒', 'label' => '哪吒', 'disabled' => false],
                        ['value' => '木吒', 'label' => '木吒', 'disabled' => false],
                        ['value' => '二郎神', 'label' => '二郎神', 'disabled' => true],
                        ['value' => '哮天犬', 'label' => '哮天犬', 'disabled' => false],
                        ['value' => '太白金星', 'label' => '太白金星', 'disabled' => false],
                    ])->defaultValue('猪八戒')->attribute(['data-attr' => 1])->placeholder('请选择通天塔')->uiClass('w-350 float-none')->style(['font-size' => '13px'])
                        ->disabled(false)->search_fuzzy(true)->search(true)->search_caseSensitive(true)->creatable(true)->help('这只是一个简单的帮助！')->unspread(),
                    'e' => $this->toolbarFilter->selectLink()->label('下拉选择联动')->initOptions([
                        ['value' => '1', 'text' => '东莞市1'],
                        ['value' => '2', 'text' => '东莞市2'],
                        ['value' => '3', 'text' => '东莞市3'],
                    ])->route('/admin/test1')->targetLink('f')->start()->uiClass('w-300 pr-0')->unspread(),
                    'f' => $this->toolbarFilter->selectLink()->label(null)->initOptions([
                        ['value' => '11', 'text' => '东莞市11'],
                        ['value' => '21', 'text' => '东莞市21'],
                        ['value' => '31', 'text' => '东莞市31'],
                    ])->route('/admin/test2')->targetLink('g')->through()->uiClass('w-200 pr-0')->style('margin-left:-1px;')->unspread(),
                    'g' => $this->toolbarFilter->selectLink()->label(null)->initOptions([
                        ['value' => '111', 'text' => '东莞市111'],
                        ['value' => '211', 'text' => '东莞市211'],
                        ['value' => '311', 'text' => '东莞市311'],
                    ])->end()->uiClass('w-200 float-none')->style('margin-left:-1px;')->unspread(),
                    'c' => $this->toolbarFilter->radio()->label('单选框')->options(['中国人民共和国','弹丸倭寇小国日本','美利坚合众国','大众起源地德国'])->uiClass('w-550 float-none')->style('padding:0;margin-left:-1px;')->unspread(),
                    'd' => $this->toolbarFilter->checkbox()->label('多选框')->options(['清华大学', '北京大学', '剑桥大学', '麻省理工学院'])->uiClass('w-400')->style('padding:0;margin-left:-1px;')->unspread(),
                ])
                ->setToolbarTab([
                    $this->toolbarTab->title('选项1')->params(['param1' => 1])->checked(),
                    $this->toolbarTab->title('选项2')->params(['param1' => 2]),
                    $this->toolbarTab->title('选项3')->params(['param1' => 3]),
                    $this->toolbarTab->title('选项4')->params(['param1' => 4]),
                    $this->toolbarTab->title('选项5')->params(['param1' => 5]),
                ])
                ->setRowOperation([
                    $this->rowOperation->modal()->title('编 辑')->route('ymtest/table/demo')->params(['id'])->titleMaxminBtnDisplay(),
                    $this->rowOperation->ajax()->title('删除1')->route('ymtest/table/demo')->params(['id'])->method('post')->group(),
                    $this->rowOperation->ajax()->title('删除2')->route('ymtest/table/demo')->params(['id'])->method('post')->group(),
                ]);
        }

        return $tableBuilder->render();
    }

    public function actionDemo()
    {
        $viewBuilder = $this->viewBuilder;
        if ($this->isAjax) {
            if ($viewBuilder->builderId == 'Tmtest_Table_Demo_Table') {
                return TableBuilder::instance(['id' => 'Tmtest_Table_Demo_Table'])
                    ->setPage(false)
                    ->setQuery(function () {
                        $data = [];
                        for ($i = 0; $i < 10; $i++) {
                            $data[] = [
                                'id' => $i,
                                'name' => Str::random(5),
                                'sex' => time() % 2 === 0 ? '男' : '女',
                                'age' => rand(18, 80),
                                'classGrade' => rand(1, 9),
                            ];
                        }
                        return $data;
                    })
                    ->setOrderBy(['id' => SORT_DESC])
                    ->setColumns([
                        'id',
                        'name',
                        'sex',
                        'age',
                        'classGrade',
                    ])
                    ->render();
            } else {
                //return $this->asOk('用户信息已提交，系统和机器人认真审核中，请您等待1-3个工作日后，查看审核结果。');
                return $this->asFail('系统审核失败，原因：您的账号姓名没有正确填写，身份证信息已过期，请您到户籍所在地重新办理后，重新提交审核，谢谢您的理解！');
            }

        }else {
            $viewBuilder->form
                ->setId('Tmtest_Table_Demo_Form')
                ->setFormControl([
                    'a' => $this->formControl->text()->label('KEY')->required(),
                ])
                ->setSubmitBtn()
                ->setFooterFixed(false)
                //->setAutoClose()
                ->setSubmittedCalls([
                    'parent' => 'Table_Index_Table',
                ], [
                    'self' => 'Tmtest_Table_Demo_Table',
                ]);
            $viewBuilder->table
                ->setId('Tmtest_Table_Demo_Table')
                ->setPage(false)
                ->setTableHead([
                    $this->tableHead->field('id')->title('ID'),
                    $this->tableHead->field('name')->title('名称'),
                    $this->tableHead->field('sex')->title('性别'),
                    $this->tableHead->field('age')->title('年龄'),
                    $this->tableHead->field('classGrade')->title('班级'),
            ])->setToolbarRefresh();

            return $viewBuilder->setPartial()->render();
        }
    }

    /**
     * 导出
     * @return string
     * @throws \yii\base\InvalidConfigException
     */
    public function actionExport()
    {
        $export = ExportBuilder::instance(['id' => 'BID_Table_Export']);
        if ($export->isAjax) {
            $export->setQuery(function () {
                $data = [];
                foreach ($this->getData() as $k => $i) {
                    if ($k < 5000) {
                        $data[] = [
                            'id' => $i + 1,
                            'name' => Str::random(5),
                            'age' => rand(16, 50),
                            'class' => 'Grade ' . ($i + 1),
                            'county' => 'China',
                            'sex' => range(1, 2),
                        ];
                    }
                }
                return $data;
            })->setColumns([
                'ID' => 'id',
                '姓名' => 'name',
                '年龄' => 'age',
                '班级' => 'grade',
                '国家' => 'county',
                '性别' => function ($row, $columnDependency) {
                    return $columnDependency[array_rand($columnDependency)];
                },
                '常量1' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量2' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量3' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量4' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量5' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量51' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量6' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量7' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量8' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量9' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量10' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量11' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量12' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量13' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量14' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量15' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量16' => function () { return '这是一段文本。你真是个好人呢。'; },
                '常量17' => function () { return '这是一段文本。你真是个好人呢。'; },
            ])->setColumnDependency(function ($pageData) {
                return ['i', 'love', 'you'];
            });
        } else {
            $headPage = H5::alert('这是页面头部切点。', 'normal', false);
            $footerPage = H5::printButton();
            $export->setTitle('VIP会员下载')
                ->setPartial()
                //->registerPointcut($headPage)
                ->registerPointcut($footerPage, ExportBuilder::POS_END)
                ->setTotalCount(function () {
                    // $params = $this->filteredGet;
                    // 过滤查询
                    // ...
                    return self::DATA_TOTAL;
                });
        }
        return $export->render();
    }
}